// 订单和支付服务
export interface OrderItem {
  productId: number
  productName: string
  productImage: string
  price: number
  quantity: number
}

export interface Order {
  id: string
  items: OrderItem[]
  totalAmount: number
  status: 'pending' | 'paid' | 'cancelled' | 'completed'
  createTime: string
  payTime?: string
  userId: string
}

export interface PaymentResult {
  success: boolean
  orderId: string
  paymentId?: string
  message: string
}

class OrderService {
  private orders: Order[] = []

  // 创建订单
  async createOrder(items: OrderItem[], userId: string = 'user_001'): Promise<Order> {
    const orderId = `ORDER_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    const totalAmount = items.reduce((sum, item) => sum + (item.price * item.quantity), 0)
    
    const order: Order = {
      id: orderId,
      items,
      totalAmount,
      status: 'pending',
      createTime: new Date().toISOString(),
      userId
    }

    this.orders.push(order)
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    console.log('订单创建成功:', order)
    return order
  }

  // 支付订单
  async payOrder(orderId: string): Promise<PaymentResult> {
    const order = this.orders.find(o => o.id === orderId)
    
    if (!order) {
      return {
        success: false,
        orderId,
        message: '订单不存在'
      }
    }

    if (order.status !== 'pending') {
      return {
        success: false,
        orderId,
        message: '订单状态不正确'
      }
    }

    // 模拟支付处理
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟支付成功率90%
    const isSuccess = Math.random() > 0.1
    
    if (isSuccess) {
      order.status = 'paid'
      order.payTime = new Date().toISOString()
      
      const paymentId = `PAY_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
      
      console.log('支付成功:', { orderId, paymentId })
      
      return {
        success: true,
        orderId,
        paymentId,
        message: '支付成功'
      }
    } else {
      console.log('支付失败:', orderId)
      
      return {
        success: false,
        orderId,
        message: '支付失败，请重试'
      }
    }
  }

  // 获取订单详情
  async getOrder(orderId: string): Promise<Order | null> {
    await new Promise(resolve => setTimeout(resolve, 200))
    return this.orders.find(o => o.id === orderId) || null
  }

  // 获取用户订单列表
  async getUserOrders(userId: string = 'user_001'): Promise<Order[]> {
    await new Promise(resolve => setTimeout(resolve, 300))
    return this.orders.filter(o => o.userId === userId)
  }

  // 取消订单
  async cancelOrder(orderId: string): Promise<boolean> {
    const order = this.orders.find(o => o.id === orderId)
    
    if (!order || order.status !== 'pending') {
      return false
    }

    order.status = 'cancelled'
    await new Promise(resolve => setTimeout(resolve, 200))
    
    console.log('订单已取消:', orderId)
    return true
  }
}

// 导出单例实例
export const orderService = new OrderService()

// 支付方式枚举
export enum PaymentMethod {
  WECHAT = 'wechat',
  ALIPAY = 'alipay',
  CREDIT_CARD = 'credit_card'
}

// 支付参数接口
export interface PaymentParams {
  orderId: string
  method: PaymentMethod
  returnUrl?: string
}

// 模拟支付SDK
export class PaymentSDK {
  // 微信支付
  static async wechatPay(params: PaymentParams): Promise<PaymentResult> {
    console.log('调用微信支付:', params)
    
    // 模拟微信支付流程
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    return orderService.payOrder(params.orderId)
  }

  // 支付宝支付
  static async alipay(params: PaymentParams): Promise<PaymentResult> {
    console.log('调用支付宝支付:', params)
    
    // 模拟支付宝支付流程
    await new Promise(resolve => setTimeout(resolve, 1200))
    
    return orderService.payOrder(params.orderId)
  }

  // 信用卡支付
  static async creditCardPay(params: PaymentParams): Promise<PaymentResult> {
    console.log('调用信用卡支付:', params)
    
    // 模拟信用卡支付流程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    return orderService.payOrder(params.orderId)
  }
}